package com.nyist.springcloud.controller;

import com.nyist.springcloud.ResultVO;
import com.nyist.springcloud.entities.Payment;
import com.nyist.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author yangxiaogen
 * @date 2021/1/21 15:46
 */
@RestController
@RequestMapping("/pay")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/create")
    public ResultVO<Payment> createPay(@RequestBody Payment payment) {
        log.info("开始插入支付数据:", payment);
        ResultVO<Payment> paymentResultVO = new ResultVO<>();
        Payment insertPay = paymentService.insertPay(payment);
        if (insertPay != null) {
            paymentResultVO.setCode("200");
            paymentResultVO.setMessage("成功");
            paymentResultVO.setData(insertPay);
        } else {
            paymentResultVO.setCode("400");
            paymentResultVO.setMessage("失败");
        }
        return paymentResultVO;
    }

    @PostMapping("/get")
    public ResultVO<Payment> getPayment(@RequestBody Payment result) {
        ResultVO<Payment> paymentResultVO = new ResultVO<>();
        Payment payment = paymentService.queryPaymentById(result.getId());
        if (payment != null) {
            log.info("开始--查询--支付数据:", serverPort, payment);
            paymentResultVO.setCode("200");
            paymentResultVO.setMessage("成功" + serverPort);
            paymentResultVO.setData(payment);
        } else {
            paymentResultVO.setCode("400");
            paymentResultVO.setMessage("失败");
        }
        return paymentResultVO;
    }

    @PostMapping(value = "/lb")
    public ResultVO<Payment> getPaymentLb(@RequestBody Payment payment) {
        ResultVO<Payment> paymentResultVO = new ResultVO<>();

        log.info("开始--查询--支付数据:  8001 ", serverPort);
        paymentResultVO.setCode("200");
        paymentResultVO.setMessage("成功" + serverPort);

        return paymentResultVO;
    }

    @PostMapping(value = "/feign/timeout")
    public ResultVO<Payment> getPaymentTimeout(@RequestBody Payment payment) {
        ResultVO<Payment> paymentResultVO = new ResultVO<>();

        try {
            log.info("-------------------------开始休眠, 2秒后启动");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("开始--查询--支付数据:  8001 ", serverPort);
        paymentResultVO.setCode("200");
        paymentResultVO.setMessage("成功" + serverPort);

        return paymentResultVO;
    }

}
